<?php


namespace app\api\model\order;


use app\logic\model\OrderOpusModel as OrderOpus;
use app\logic\model\SettingModel;
use app\api\common;
use app\api\model\OpusNumberModel;
use app\api\model\UserModel;
use think\facade\Db;

class OrderOpusNumberModel extends OrderOpus
{
    /**
     * 创建原创作品订单
     * @param $opusNumberId array 作品编号标识
     */
    function createOrder($opusNumberId){
        global $user;
        $opusModel=new OpusNumberModel();
        $opusNumber=$opusModel->getFindByid($opusNumberId);
        $each_price=$opusNumber['each_price'];//金额
        Db::startTrans();
        try {
            /**佣金-开始**/
            $commissionPrice=$this->getCommissionPrice($opusNumber);
            $member_uid=$commissionPrice['member_uid'];
            $member_commission_price=$commissionPrice['member_commission_price'];
            $head_uid=$commissionPrice['head_uid'];
            $head_commission_price=$commissionPrice['head_commission_price'];
            /**佣金-结束**/
            /**平台佣金-开始**///平台佣金=藏家服务费比例*作品金额
            $collectors=(new UserModel())->getFindByid($opusNumber['owner_uid']);
            if(empty($collectors)){
                show_json('createOpusNumber.no_collectors');
            }
            if($collectors['collectors_rate']==-1){
                $collectors['collectors_rate']=(new SettingModel())->get_value('collectors_rate');
            }
            $platform_price=$each_price*round($collectors['collectors_rate']/100,2);
            /**平台佣金-结束**/
            /**溢价金额-开始**///溢价金额=当前订单金额-该编号上一个订单金额
            $prevOrderOpus=(new OrderOpusModel())->getPrevOrderOpus($opusNumberId);
            if(!empty($prevOrderOpus)){
                $premium_price=$each_price-$prevOrderOpus['price'];
            }else{
                //如果没有上一次订单，溢价金额就是订单金额
                $premium_price=$each_price;
            }
            /**作家版权费收益-开始**///作家版权费收益=溢价金额*作家版权费比例
            $write_copyright_price=0;
            if($premium_price>0){
                $writer_copyright_rate=(new SettingModel())->get_value('writer_copyright_rate');
                $write_copyright_price=$premium_price*round($writer_copyright_rate/100,2);
            }
            /**作家版权费收益-结束**/
            /**卖家收益-开始**///卖家收益=作品金额-作家版权费收益-平台佣金-团员佣金金额-团长佣金金额
            $seller_price=$each_price-$write_copyright_price-$platform_price-$member_commission_price-$head_commission_price;
            /**卖家收益-结束**/
            /**创建主表-开始**/
            $orderCreateData=array(
                'buyer_id'=>$user['id'],
                "ordersn"=>common::getOrdersn('OQ',rand(10000,99999)),
                "price"=>$each_price,
                "status"=>0,//支付状态为0
                'seller_id'=>$opusNumber['owner_uid'],
                'is_commission'=>$commissionPrice['is_commission'],
                'member_uid'=>$member_uid,
                'member_commission_price'=>$member_commission_price,
                'head_uid'=>$head_uid,
                'head_commission_price'=>$head_commission_price,
                'create_time'=>time(),
                'write_copyright_price'=>0,
                'seller_price'=>$seller_price,
                'premium_price'=>$premium_price,
                'platform_price'=>$platform_price,
                'opus_id'=>$opusNumber['opus_id'],
            );
            $order_id=Db::name("order_pay")->insertGetId($orderCreateData);
            /**创建主表-结束**/

            $createData=array(
                'ordersn'=>common::getOrdersn('ONQ',rand(100,999)),
                'opus_number_id'=>$opusNumberId,
                'opus_id'=>$opusNumber['opus_id'],
                'buyer_id'=>$user['id'],
                'seller_id'=>$opusNumber['owner_uid'],//购买作品编码，卖家一定是藏家
                'status'=>0,
                'price'=>$each_price,
                'premium_price'=>$premium_price,
                'platform_price'=>$platform_price,
                'is_commission'=>$commissionPrice['is_commission'],
                'commission_price'=>$commissionPrice['commission_price'],
                'member_uid'=>$member_uid,
                'member_commission_price'=>$member_commission_price,
                'head_uid'=>$head_uid,
                'head_commission_price'=>$head_commission_price,
                'write_copyright_price'=>$write_copyright_price,
                'seller_price'=>$seller_price,
                'order_pay_id'=>$order_id
            );
            $this->save($createData);
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return ['code'=>-1,'msg'=>$e->getMessage()];
        }
        return ['code'=>0,'order_id'=>$order_id];
    }

    function getCommissionPrice($opus){
        global $user;
        $agent=(new UserModel)->getAgent();
        $return=array(
            'is_commission'=> $opus['is_commission']==1,
            'commission_price'=>0,
            'member_commission_price'=>0,
            'member_uid'=>$agent['member_uid'],
            'head_commission_price'=>0,
            'head_uid'=>$agent['head_uid'],
        );
        if($return['is_commission']){
            if(!empty($return['member_uid'])||!empty($return['head_uid'])){
                //分销佣金
                $price = round($opus['each_price'] * $opus['commission_rate'] / 100, 2);
                if($agent['member_uid']){
                    $head_user=(new UserModel)->getFindByid($agent['head_uid']);
                    //获取团长佣金开始
                    $head_price = round($price * $head_user['head_commission_rate'] / 100, 2);
                    //团长佣金
                    $return['head_commission_price'] = $head_price;
                    //团员佣金
                    $return['member_commission_price'] = $price - $head_price;
                }else{
                    $return['head_commission_price']=$price;
                }
                $return['price']=$price;
            }

        }
        return $return;
    }

    function getList($param,$field="*",$limit,$isPage=true){
        $list=$this->where(function($q) use ($param){
            if(check_request($param,'order_pay_id')){
                $q->where('order_pay_id',$param['order_pay_id']);
            }
        })->field($field);
        if($isPage){
            $list=$list->paginate($limit);
        }else{
            $list=$list->limit($limit)->select();
        }
        if(!$list->isEmpty()){
            return $list->toArray();
        }
        return $list;
    }
    function updateOrder($id,$data){
        return $this->where('id',$id)->save($data);
    }

    function getFindById($id){
        return $this->find($id);
    }
}